import json
import re

from flask import Blueprint, Response

from common.helper import json_resp
from modules.amis.component.base import Option, SelectMode, Level, Size, ActionType, DateShortcuts, FormMode, InitEvent, \
    OnEvent, InitedEvent, Toast, ToastItem, LeftAndRight, Action, Function, VariableItem, ColorFormat
from modules.amis.component.datainput import InputText, InputPassword, InputEmail, InputUrl, Select, InputDateRange, \
    InputDate, Form, Checkboxes, Static, InputCity, InputColor, InputFormula, InputYear, InputMonth, InputQuarter, \
    DiffEditor, InputExcel, InputRichText, Radios, Group, InputArray, InputImage, InputRating, Checkbox, InputTag, \
    TextArea, Transfer, TransferPicker, JSONSchemaEditor
from modules.amis.component.datashow import Table, Column, Image, StaticImage, Calendar, ScheduleItem, Carousel, \
    CarouselItem, Chart
from modules.amis.component.feedback import Dialog
from modules.amis.component.function import Button, UrlButton, EmailButton, Service, AjaxButton, Custom
from modules.amis.component.layout import Divider, Page, Container, CollapseGroup, Collapse, Panel, Grid, GridColumn

amis_bp = Blueprint("amis", __name__)


# @amis_bp.after_request
# def handle_after_request(response: Response):
#     content = str(response.data, "utf-8")
#
#     pattern = '\$\$\$\{(.*?)\}\$\$\$'
#     matches = re.findall(pattern, content, re.DOTALL)
#     for item in matches:
#         content = content.replace("\"$$${" + item + "}$$$\"", "eval(" + item + ")")
#     content = content.replace("\n", "")
#     response.data = bytes(content, "utf-8")
#     return response


@amis_bp.route("/input_text")
def input_test():
    user_name_input = InputText(
        name="user_name",
        label="用户名",
    )
    user_name_input.placeholder = "请输入用户名"
    user_name_input.clearable = True
    user_name_input.required = True
    user_name_input.validations = {
        "minimum": 3
    }
    user_name_input.validationErrors = {
        "minimum": "同学，最少输入$1以上的数字哈"
    }

    divider = Divider()
    user_sex_input = InputText(
        name="user_sex",
        label="性别",
        placeholder="请选择性别"
    )
    user_sex_input.options = [Option("男", "男"), Option("女", "女")]

    height_input = InputText(
        name="height",
        label="身高",
    )
    height_input.clearable = True
    height_input.suffix = "米"
    height_input.prefix = "身高"

    aihao_input = InputText(
        name="aihao",
        label="爱好",
        value="足球",
    )
    aihao_input.multiple = True
    aihao_input.placeholder = "爱好"
    aihao_input.options = ["篮球", "足球", "乒乓球"]

    email_input = InputEmail(
        name="email",
        label="邮箱地址",
    )

    password_input = InputPassword(
        name="pwd",
        label="用户密码",
    )

    url_input = InputUrl(
        name="url",
        label="网页地址",
    )

    city = InputCity(name="city", label="城市")

    color = InputColor(name="color", label="颜色", format=ColorFormat.hex, value="#D0021B")

    _color = Static(name="color")

    sex_radio = Radios(name="sex", label="性别", options=[
        Option(label="男", value="male"),
        Option(label="女", value="female")
    ])

    color_arr = InputArray(name="array", label="颜色集合", value="#D0021B", items=[
        InputColor(format=ColorFormat.hex)
    ])

    return Page(title="测试文本框",
                data={
                    "user_name": "suncht",
                    "user_sex": "男",
                },
                body=Form(
                    mode=FormMode.horizontal,
                    body=[
                        Group(body=[user_name_input,
                                    user_sex_input,
                                    height_input,
                                    ]),
                        Group(body=[
                            aihao_input,
                            email_input,
                            password_input,
                        ]),
                        Group(body=[
                            # divider,
                            url_input,
                            city,
                            color,
                            # _color,
                        ]),
                        Group(body=[
                            sex_radio,
                            color_arr,
                        ]),
                    ])).render()
    # return Page(title="test", body={
    #     "type": 'input-text',
    #     "label": "asdfasdf",
    # }).render()


@amis_bp.route("/select")
def select_test():
    options_01 = [Option("男", "male"), Option("女", "female")]
    select_01 = Select(name="sex", options=options_01)
    select_01.label = "性别"
    # select_01.menuTpl = "<div>${label} 值：${value}, 当前是否选中: ${checked}</div>"
    select_01.checkAll = True
    select_01.checkAllLabel = "全部"
    select_01.clearable = True
    select_01.multiple = True
    select_01.searchable = True
    select_01.value = "male"

    # options_02 = [Option("法师", children=[{"label": "诸葛亮", "value": "zhugeliang"}])]
    options_02 = [
        Option("法师", children=[Option("诸葛亮", "zhugeliang")]),
        Option("战士", children=[Option("曹操", "caocao"), Option("钟无艳", "zhongwuyan")]),
    ]
    select_02 = Select(name="a", label="职业a", options=options_02)
    select_02.selectMode = SelectMode.group
    select_02.placeholder = "请选择职业"
    select_02.searchable = True

    options_03 = [
        Option("诸葛亮", "zhugeliang", position="中单"),
        Option("曹操", "caocao", position="上单"),
        Option("钟无艳", "zhongwuyan", position="下单"),
    ]
    select_03 = Select(name="b", label="职业b", options=options_03)
    select_03.selectMode = SelectMode.table
    select_03.placeholder = "请选择职业"
    select_03.searchable = True
    select_03.multiple = True
    select_03.columns = [
        {
            "name": "label",
            "label": "英雄"
        },
        {
            "name": "position",
            "label": "位置"
        }
    ]

    options_04 = [
        Option("法师", children=[Option("诸葛亮", "zhugeliang")]),
        Option("战士", children=[Option("曹操", "caocao"), Option("钟无艳", "zhongwuyan")]),
    ]
    select_04 = Select(name="c", label="职业c", options=options_04)
    select_04.selectMode = SelectMode.tree
    select_04.placeholder = "请选择职业"
    select_04.searchable = True

    return json_resp(Page(title="测试下拉框", body=[
        select_01,
        select_02,
        select_03,
        select_04,
    ]).render())


@amis_bp.route("/button")
def button_test():
    button_01 = Button(label="提交", level=Level.primary)
    button_01.size = Size.sm
    button_01.actionType = ActionType.toast
    button_01.toast = Toast(timeout=3000, items=[
        ToastItem(body="<strong>Hello</strong> <span>world</span>"),
    ])
    button_01.icon = "fa fa-plus"

    button_02 = Button(actionType=ActionType.url, label="跳转到百度", level=Level.success)
    button_02.size = Size.sm
    button_02.className = "mx-2"
    button_02.url = "https://www.baidu.com"

    button_03 = Button(actionType=ActionType.dialog, label="弹个框", level=Level.danger)
    button_03.size = Size.sm
    button_03.dialog = Dialog(title="测试对话框", body="系统提示", size=Size.full)
    button_03.debug = True

    url_button_04 = UrlButton(label="打开 Baidu", level=Level.warning, url="http://www.baidu.com", blank=True)
    url_button_04.className = "mx-2"

    email_button_05 = EmailButton(label="发送邮件", to="amis@baidu.com", cc="baidu@baidu.com", subject="这是邮件主题",
                                  body="这是邮件正文")
    email_button_05.className = "mx-2"

    return json_resp(Page(title="<strong>Hello</strong> <span>world</span>", body=[
        button_01,
        button_02,
        button_03,
        url_button_04,
        email_button_05,
    ]).render())


@amis_bp.route("/input_date")
def input_date_test():
    input_date_01 = InputDate(name="input_date", label="日期")
    input_date_01.embed = False
    input_date_01.shortcuts = [DateShortcuts.n_daysago.value % 7, DateShortcuts.n_dayslater.value % 7]
    input_date_01.debug = True

    input_date_02 = InputDateRange(name="input_date_range", label="日期")

    return json_resp(Page(title="测试日期", body=[
        input_date_01,
        input_date_02,
    ]).render())


@amis_bp.route("/form")
def form_test():
    view_mode = True

    button1 = Button(label="编辑模式", onEvent=
    {
        "click": {
            "actions": [
                {
                    "actionType": "nonstatic",
                    "componentId": "userInfo"
                }
            ]
        }
    }
                     )

    button2 = Button(label="查看模式", onEvent=
    {
        "click": {
            "actions": [
                {
                    "actionType": "static",
                    "componentId": "userInfo"
                }
            ]
        }
    }
                     )

    user_name_input = InputText(
        name="user_name",
        label="用户名",
    )
    user_name_input.placeholder = "请输入用户名"
    user_name_input.clearable = True
    user_name_input.required = True
    user_name_input.validations = {
        "minLength": 3
    }
    user_name_input.validationErrors = {
        "minLength": "同学，最少输入$1以上的字符串哈"
    }

    user_sex_input = InputText(
        name="user_sex",
        label="性别",
        placeholder="请选择性别"
    )
    user_sex_input.options = [Option("男", "男"), Option("女", "女")]

    height_input = InputText(
        name="height",
        label="身高",
    )
    height_input.clearable = True
    height_input.suffix = "米"
    height_input.prefix = "身高"

    aihao_input = InputText(
        name="aihao",
        label="爱好",
        value="足球",
    )
    aihao_input.multiple = True
    aihao_input.placeholder = "爱好"
    aihao_input.options = ["篮球", "足球", "乒乓球"]

    email_input = InputEmail(
        name="email",
        label="邮箱地址",
    )

    password_input = InputPassword(
        name="pwd",
        label="用户密码",
    )

    url_input = InputUrl(
        name="url",
        label="网页地址",
    )

    image = InputImage(
        name="pic",
        label="照片",
        src="https://q6.itc.cn/q_70/images03/20240509/188dfa5b4ad744928774ca951f23b52e.jpeg",
        receiver="https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/upload/file",
        # crop=True,
    )

    # if view_mode:
    #     image = StaticImage(
    #         name="pic",
    #         label="照片",
    #         enlargeAble=True,
    #         src="https://q6.itc.cn/q_70/images03/20240509/188dfa5b4ad744928774ca951f23b52e.jpeg"
    #     )

    rating = InputRating(name="rating", label="评分", count=6, value=3, texts={
        "1": "好1",
        "2": "好2",
        "3": "好3",
        "4": "好4",
        "5": "好5",
        "6": "好6",
    })

    tag = InputTag(name="tag", label="标签", maxTagCount=5, enableBatchAdd=True, separator=",", options=[
        Option(label="苹果", value="Apple"),
        Option(label="香蕉", value="Banana"),
        Option(label="黑莓", value="Blackberry"),
        Option(label="蓝莓", value="Blueberry"),
        Option(label="樱桃", value="Cherry"),
        Option(label="杨桃", value="Carambola"),
        Option(label="椰子", value="Coconut"),
        Option(label="猕猴桃", value="Kiwifruit"),
        Option(label="柠檬", value="Lemon"),
        Option(label="菠萝", value="Pineapple"),
    ])

    transfer = TransferPicker(name="transfer", label="英雄", selectTitle="待选区", resultTitle="已选区",
                              searchable=True, resultSearchable=True, sortable=True,
                              options=[
                                  Option(label="诸葛亮", value="zhugeliang"),
                                  Option(label="曹操", value="caocao")
                              ])

    desc = TextArea(name="desc", label="描述", minRows=5, showCounter=True)

    calendar = Calendar(label="日历", largeMode=True,
                        todayActiveStyle={
                            "backgroundColor": "#ef4444 !important",
                            "color": "#f8f9fa",
                            "border": "none",
                            "borderRadius": "15px"
                        },
                        schedules=[
                            ScheduleItem(startTime="2024-06-05 23:59:59", endTime="2024-06-06 23:59:59",
                                         content="测试as达到来啊是", className="bg-primary"
                                         )
                        ], scheduleAction=Dialog(title="详情", dialog={
            "title": "弹框标题",
            "body": {
                "type": "table",
                "columns": [
                    {
                        "name": "time",
                        "label": "时间"
                    },
                    {
                        "name": "content",
                        "label": "内容"
                    }
                ],
                "data": "${scheduleData}"
            }
        }))

    jsonSchemaEditor = JSONSchemaEditor(label="字段类型", name="json", mini=True, advancedSettings={
        "string": [
            {
                "type": "input-text",
                "name": "maxLength",
                "label": "Max Length"
            }
        ],
        "number": [
            {
                "type": "input-number",
                "name": "max",
                "label": "Max"
            }
        ]
    })

    form = Form(name="userInfo", id="userInfo", title="用户信息", data={
        "user_name": "张三",
        "url": "https://www.google.com",
        "user_sex": "男",
        "height": 170,
        "email": "123456@163.com",
    },
                # api="https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/mock2/form/saveForm",
                api="/api/demo/saveUserInfo",
                body=[
                    button1,
                    button2,
                    user_name_input,
                    user_sex_input,
                    height_input,
                    aihao_input,
                    email_input,
                    password_input,
                    url_input,
                    image,
                    rating,
                    tag,
                    transfer,
                    desc,
                    calendar,
                    jsonSchemaEditor,
                ])
    form.mode = FormMode.horizontal
    form.horizontal = {
        "left": 1,
        "right": 10,
        "offset": 2
    }
    return json_resp(Page(title="测试表单", data={
        "editable": True
    },
                          body=[
                              form
                          ]).render())


@amis_bp.route("/event")
def event_test():
    page = Page(title="测试表单", body=[])
    page.onEvent = OnEvent(events=[
        InitEvent().add_action({
            "actionType": "dialog",
            "dialog": {
                "title": "弹框标题",
                "body": "这是一个弹框"
            }
            # "args": {
            #     "msgType": "info",
            #     "msg": "init"
            # }
        }),
        InitedEvent().add_action({
            "actionType": "toast",
            "args": {
                "msgType": "info",
                "msg": "inited"
            }
        })
    ])

    return json_resp(page.render())


@amis_bp.route("/collapse")
def collapse_test():
    collapse_group01 = CollapseGroup(activeKey=["1"], body=[
        Collapse(header="标题1", body="这里是内容1", key="1"),
        Collapse(header="标题2", body="这里是内容2", key="2"),
        Collapse(header="标题3", body="这里是内容3", key="3"),
    ])
    collapse_group02 = CollapseGroup(activeKey=["1"], accordion=True, body=[
        Collapse(header="标题1", body="这里是内容1", key="1"),
        Collapse(header="标题2", body="这里是内容2", key="2"),
        Collapse(header="标题3", body="这里是内容3", key="3"),
    ], expandIconPosition=LeftAndRight.right)
    collapse_group03 = CollapseGroup(activeKey=["1"], accordion=True, body=[
        Collapse(header="标题1", body="这里是内容1", key="1"),
        Collapse(header="标题2", body="这里是内容2", key="2"),
        Collapse(header="标题3", body="这里是内容3", key="3"),
    ], expandIcon={
        "type": "icon",
        "icon": "fa fa-caret-right"
    })
    return json_resp(Page(title="折叠器", body=[
        Panel(title="普通模式", body=collapse_group01),
        Panel(title="手风琴模式", body=collapse_group02),
        Panel(title="自定义图标", body=collapse_group03),
    ]).render())


@amis_bp.route("/table")
def table_test():
    service_01 = Service(api="https://aisuda.bce.baidu.com/amis/api/mock2/sample?perPage=5", body=[
        Table(source="${rows}", columnsTogglable=False, footable=True, columns=[
            Column(name="engine", label="引擎", width="40%", popOver=True, breakpoint="*"),
            Column(name="id", label="Id", width=150),
            Column(name="grade", label="Grade"),
            Column(name="version", label="版本", searchable=True),
            Column(name="browser", label="浏览器", filterable={
                "options": [
                    "Internet Explorer 4.0",
                    "Internet Explorer 5.0"
                ]
            }),
            Column(name="platform", label="平台", copyable=True),
        ],
              itemAction=Button(actionType=ActionType.dialog,
                                dialog=Dialog(title="详情",
                                              body="当前行的数据 browser: ${browser}, version: ${version}"))
              ,
              itemActions=[Button(label="编辑", actionType=ActionType.dialog, level=Level.danger,
                                  dialog=Dialog(title="详情",
                                                body="当前行的数据 browser: ${browser}, version: ${version}")),
                           AjaxButton(label="删除", confirmText="确认要删除？",
                                      api="https://aisuda.bce.baidu.com/amis/api/mock2/form/saveForm"),
                           ],
              placeholder="暂时无任何数据")
    ])
    return json_resp(Page(title="表格", body=[
        service_01
    ]).render())


@amis_bp.route("/custom")
def custom_test():
    #     html = """
    #     {
    #   type: 'page',
    #   title: '21',
    #   body: {
    #     type: 'form',
    #     title: 'custom',
    #     body: [
    #       {
    #         type: 'custom',
    #         name: 'my-custom',
    #         html: `
    #         <ol>
    #           <li v-for="todo in todos">
    #             {{ todo.text }}
    #           </li>
    #         </ol>
    #         `,
    #         label: '21',
    #         onMount: (dom, data, onChange, props) => {
    #           const app = new Vue({
    #             el: dom,
    #             data: {
    #               todos: [
    #                 { text: 'hello' },
    #                 { text: 'world' },
    #                 { text: 'vue' }
    #               ]
    #             }
    #           })
    #         }
    #       }
    #     ]
    #   }
    # }
    #     """
    #     a = json.loads(html)
    #     return html, 200, {'Content-Type': 'text/plain'}
    custom_01 = Custom(name="aa",
                       label="自定义组件",
                       html='''
                                <ol>
                                  <li v-for="todo in todos">
                                    {{ todo.text }}
                                  </li>
                                </ol>
                            ''',
                       onMount=Function('''
                       (dom, data, onChange, props) => {
                          const app = new Vue({
                            el: dom,
                            data: {
                              todos: [
                                { text: 'hello' },
                                { text: 'world' },
                                { text: 'vue' }
                              ]
                            }
                          })
                       }
                       '''),
                       )

    city = InputCity(name="city", label="城市")

    color = InputColor(name="color", label="颜色")

    formula = InputFormula(name="formula", label="公式", evalMode=False, value="my name is \\${name}", variables=[
        VariableItem(label="表单字段", children=[
            VariableItem(label="文章名", value="name", tag="文本"),
            VariableItem(label="作者", value="author", tag="文本")
        ])
    ])

    year = InputYear(name="year", label="年份")
    month = InputMonth(name="month", label="月份")
    quarter = InputQuarter(name="quarter", label="季度")
    diffEditor = DiffEditor(name="diff", diffValue="${formula}", label="文件对比", language="java")
    excel = InputExcel(name="excel", label="上传 Excel", autoFill={
        "fileName": "${filename}"
    })
    static = Static(name="diff")

    richtext = InputRichText(name="richtext", options={
        # "width": 600,
        "height": 600,
        "plugins": [
            'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',
            'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime',
            'media', 'table', 'emoticons', 'template', 'help'
        ],
        "toolbar": 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | ' +
                   'bullist numlist outdent indent | link image | print preview media fullscreen | ' +
                   'forecolor backcolor emoticons | help',
        # "menu": {
        #     "favs": {"title": 'My Favorites', "items": 'code visualaid | searchreplace | emoticons'}
        # },
        # "menubar": 'favs file edit view insert format tools table help',
    })
    return json_resp(Page(title="自定义组件", enablePrint=True, body=[
        Form(debug=True, body=[
            custom_01,
            city,
            color,
            formula,
            year,
            month,
            quarter,
            diffEditor,
            excel,
            static,
            richtext,
        ])
    ]).render())


@amis_bp.route("/checkboxes")
def checkboxes_page():
    checkboxes = Checkboxes(name="cc", label="复选框", joinValues=False, extractValue=True, options=[
        Option(label="aa", value="aa"),
        Option(label="bb", value="bb"),
    ])

    static = Static(tpl="${cc}")
    return json_resp(Page(title="复选框", body=[
        Form(data={
            "cc": ""
        }, body=[
            checkboxes,
            static,
        ], debug=True),
    ]).render())


@amis_bp.route("/datashow")
def datashow_page():
    carousel = Carousel(auto=True, width=500, thumbMode='contain', animation='fade', interval=3000, duration=5000,
                        options=[
                            CarouselItem(
                                image="https://internal-amis-res.cdn.bcebos.com/images/2020-1/1578395692722/4f3cb4202335.jpeg@s_0,w_216,l_1,f_jpg,q_80"),
                            CarouselItem(
                                image="https://internal-amis-res.cdn.bcebos.com/images/2020-1/1578395692942/d8e4992057f9.jpeg@s_0,w_216,l_1,f_jpg,q_80"),
                            CarouselItem(
                                image="https://internal-amis-res.cdn.bcebos.com/images/2020-1/1578395693148/1314a2a3d3f6.jpeg@s_0,w_216,l_1,f_jpg,q_80"),
                            CarouselItem(
                                image="https://internal-amis-res.cdn.bcebos.com/images/2020-1/1578395693379/8f2e79f82be0.jpeg@s_0,w_216,l_1,f_jpg,q_80"),
                        ])

    chart = Chart(api="https://3xsw4ap8wah59.cfc-execute.bj.baidubce.com/api/amis-mock/mock2/chart/chart",
                  interval=10000)

    return json_resp(Page(title="数据展示", body=[
        Form(data={
            "cc": ""
        }, body=[
            Grid(className="m-t-lg", columns=[
                GridColumn(body=carousel, md=5),
                GridColumn(body=chart, md=7),
            ])
        ], debug=False),
    ]).render())


@amis_bp.route("/login")
def login_page():
    login_form = Form(name="loginInfo", title={
        "type": "tpl",
        "tpl": "用户登录",
        "className": "inline-block w-full text-center font-bold text-md"
    })
    login_form.wrapWithPanel = False
    login_form.mode = FormMode.horizontal
    login_form.body = [
        InputText(name="userName", placeholder="用户名", label=False),
        InputPassword(name="password", placeholder="密码", label=False),
    ]

    submit_button = Button(label="登录", level=Level.primary)
    submit_button.block = True

    register_button = Button(label="免费注册", level=Level.link, actionType=ActionType.url)
    register_button.className = "text-white"

    forget_button = Button(label="忘记密码", level=Level.link, actionType=ActionType.url)
    forget_button.className = "text-white text-right"

    button_area = Container(body=[
        submit_button,
        Container(body=[
            register_button,
            forget_button,
        ])
    ])

    return json_resp(Page(body=[
        login_form,
        button_area,
    ],
        className="border-solid border rounded-xl p-4"
    ).render())

# if __name__ == '__main__':
#     html = """
#     {"type": "page", "title": "自定义组件", "body": [{"type": "custom", "label": "自定义组件", "name": "aa", "inline": false, "html": "\n                                <ol>\n                                  <li v-for=\"todo in todos\">\n                                    aaa{{ todo.text }}\n                                  </li>\n                                </ol>\n                            ", "onMount": "$$${\n                       (dom, data, onChange, props) => {\n                          const app = new Vue({\n                            el: dom,\n                            data: {\n                              todos: [\n                                { text: 'hello' },\n                                { text: 'world' },\n                                { text: 'vue' }\n                              ]\n                            }\n                          })\n                       }\n                       }$$$"}]}
#     """
#     pattern = '\$\$\$\{(.*?)\}\$\$\$'
#     matches = re.findall(pattern, html, re.DOTALL)
#     for item in matches:
#         print(item)
#         html2 = html.replace("\"$$${" + item + "}$$$\"", item)
#         print(html2)
